package com.sky.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.security.auth.login.LoginException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserMapper userMapper;
    /**
     * 登录获取用户信息
     * @param userLoginDTO
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        Map<String,String> paramMap=new HashMap<>();

        paramMap.put("appid",weChatProperties.getAppid() );
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        //调用微信接口，获得当前用户的信息尤其是openid,返回的是个json文档
        String json = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        //判断openid是否为空，空则说明登录失败
        if(openid==null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }
        //如果openid不为空，查user表，看能不能找到，如果找不到要在表里添加，找到直接返回user
        User user=userMapper.getByOpenId(openid);
        // 当前用户没有注册，需要帮他注册
        if (user==null){
            User user_new=User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            //把新注册的用户插入user表
            userMapper.insert(user_new);
            return user_new;
        }
        //如果不为空，或者注册完成返回用户对象
        return user;
    }
}
